#include "MapperAxROM.h"
#include "Log.h"

PNE_NAMESPACE_BEGIN

MapperAxROM::MapperAxROM(Cartridge &cart, std::function<void(void)> mirroring_callback)
    : Mapper(cart, Mapper::Type::AxROM),
      m_mirroring(NameTableMirroring::OneScreenLower),
      m_mirroringCallback(mirroring_callback),
      m_prgBank(0)
{
    if (cart.GetROM().size() >= 0x8000)
    {
        LOG(Level::Info) << "Using PRG-ROM OK" << std::endl;
    }

    if (cart.GetVROM().size() == 0)
    {
        m_characterRAM.resize(0x2000);
        LOG(Level::Info) << "Uses Character RAM OK" << std::endl;
    }
}

Byte MapperAxROM::ReadPRG(Address addr)
{
    if (addr >= 0x8000)
    {
        return m_cartridge.GetROM()[m_prgBank * 0x8000 + (addr & 0x7FFF)];
    }

    return 0;
}

void MapperAxROM::WritePRG(Address addr, Byte value)
{
    if (addr >= 0x8000)
    {
        m_prgBank = value & 0x07;
        m_mirroring = (value & 0x10) ? NameTableMirroring::OneScreenHigher
                                     : NameTableMirroring::OneScreenLower;
        m_mirroringCallback();
    }
}

NameTableMirroring MapperAxROM::GetNameTableMirroring()
{
    return m_mirroring;
}

Byte MapperAxROM::ReadCHR(Address addr)
{
    if (addr < 0x2000)
    {
        return m_characterRAM[addr];
    }

    return 0;
}

void MapperAxROM::WriteCHR(Address addr, Byte value)
{
    if (addr < 0x2000)
    {
        m_characterRAM[addr] = value;
    }
}
PNE_NAMESPACE_END
// DONE